package com.example.bookmanagersystem.controller;

import com.example.bookmanagersystem.entity.Book;
import com.example.bookmanagersystem.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    // 图书列表
    @GetMapping
    public String listBooks(Model model, @RequestParam(required = false) String keyword) {
        if (keyword != null && !keyword.isEmpty()) {
            model.addAttribute("books", bookService.searchBooksByTitle(keyword));
        } else {
            model.addAttribute("books", bookService.getAllBooks());
        }
        return "books/list";
    }

    // 跳转到添加图书页面
    @GetMapping("/new")
    public String showAddForm(Model model) {
        model.addAttribute("book", new Book());
        model.addAttribute("title", "添加图书");
        return "books/form";
    }

    // 保存图书
    @PostMapping
    public String saveBook(@ModelAttribute Book book) {
        bookService.addBook(book);
        return "redirect:/books";
    }


    // 跳转到编辑图书页面
    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        model.addAttribute("book", bookService.getBookById(id).orElseThrow(() -> new RuntimeException("未找到指定图书")));
        model.addAttribute("title", "编辑图书");
        return "books/form";
    }

    // 更新图书
    @PostMapping("/update/{id}")
    public String updateBook(@PathVariable Long id, @ModelAttribute Book book) {
        book.setId(id);
        bookService.updateBook(book);
        return "redirect:/books";
    }
    // 删除图书
    @GetMapping("/delete/{id}")
    public String deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
        return "redirect:/books";
    }

    // 查看图书详情
    @GetMapping("/{id}")
    public String viewBook(@PathVariable Long id, Model model) {
        model.addAttribute("book", bookService.getBookById(id).orElseThrow(() -> new RuntimeException("未找到指定图书")));
        return "books/view";
    }
}